#include "xbelview.h"
#include "smtp.h"

bool priz_new_file = false;         //признак создания нового файла
bool priz_open_file = false;        //признак открытого файла
QFile *file_open;

XbelView::XbelView(QWidget *parent) :
    QTreeView(parent)
{
    xbelmodel = new XbelModel;
    table2 = new Table2;

    setModel(xbelmodel);
    selection = new QItemSelectionModel(xbelmodel);
    setSelectionModel(selection);
    hideColumn(4);
}

void XbelView::mouseDoubleClickEvent (QMouseEvent * event)
{
    QStandardItem *item;
    QList <QModelIndex> indexs;
     if(selection->hasSelection())   {
         indexs = selection->selectedIndexes();
         item = xbelmodel->itemFromIndex(indexs[0]);
     }
    QMessageBox::about(0,tr("Нажата"),item->text());
}

void XbelView::on_actionOpen_triggered()
{
    if(on_actionClose_triggered())         //перед открытием закрываем
    {
        QString fileName =
                QFileDialog::getOpenFileName(this, tr("Открыть файл"),
                                         QDir::currentPath(),
                                         tr("XBEL Файлы (*.xbel *.xml)"));
        if (fileName.isEmpty())
            return;

        file_open = new QFile(fileName);

        if (!file_open->open(QFile::ReadOnly | QFile::Text)) {
            QMessageBox::warning(this, tr("Предупреждение Metodika"),
                                 tr("Невозможно прочитать файл %1:\n%2.")
                                 .arg(fileName)
                                 .arg(file_open->errorString()));
            return;
        }

        if (xbelmodel->read(file_open))
        {
            xbelmodel->initialize();
            //ui->statusbar->showMessage(tr("Файл загружен"), 2000);
            hideColumn(4);
            expandAll();
        }

        file_open->close();
    }

    priz_open_file = true;
}

void XbelView::on_actionSave_triggered()
{
    QString fileName =
            QFileDialog::getSaveFileName(this, tr("Сохранить файл"),
                                         QDir::currentPath(),
                                         tr("XBEL Файлы (*.xbel *.xml)"));
    if (fileName.isEmpty())
        return;

    QFile *file = new QFile(fileName);
    if (!file->open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Предупреждение Metodika"),
                             tr("Невозможно записать файл %1:\n%2.")
                             .arg(fileName)
                             .arg(file->errorString()));
        return;
    }

    if (xbelmodel->write(file))
        //statusBar()->showMessage(tr("Файл сохранен"), 2000);

    priz_new_file = false;
    priz_open_file = false;
}

void XbelView::on_actionInsert_triggered()
{
   QList <QModelIndex> indexs;
    if(selection->hasSelection())   {
        indexs = selection->selectedIndexes();
        QStandardItem *parent = xbelmodel->itemFromIndex(indexs[0]);
        xbelmodel->createItem(parent);
    }
    else
    {
        xbelmodel->createItem(xbelmodel->invisibleRootItem());
    }
}

void XbelView::on_actionInsertChild_triggered()
{
    QMessageBox::about(0,tr("Предупреждение"),tr("Будет заменена на перемещение строк"));
}

void XbelView::on_actionDelete_triggered()
{
    QList <QModelIndex> indexs;
     if(selection->hasSelection())   {
         indexs = selection->selectedIndexes();
         QStandardItem *item = xbelmodel->itemFromIndex(indexs[0]);
         xbelmodel->slot_deleteItem(item,indexs[0].row());
    }
}

void XbelView::on_actionRas_triggered()
{
    xbelmodel->slot_raschet();
}

void XbelView::on_actionNew_triggered()
{
    QFile file_new;
    file_new.setFileName("temp.temp");

    if (!file_new.open(QFile::WriteOnly)) {
        QMessageBox::warning(this, tr("Предупреждение Metodika"),
                             tr("Невозможно создать файл."));
        return;
    }

    if( xbelmodel->slot_new(&file_new))
    {
        xbelmodel->initialize();
        //ui->statusbar->showMessage(tr("Файл создан"), 2000);
        hideColumn(4);
    }
    else
    {
        return;
    }

    priz_new_file = true;
}

bool XbelView::on_actionClose_triggered()
{
    QString str_open = NULL, str_close = NULL;
    QTextStream *stream;

        QFile *file_close = new QFile("temp2.temp");
        if (!file_close->open(QFile::WriteOnly | QFile::Text)) {
            priz_open_file = false;
            }
        xbelmodel->write(file_close);
        file_close->close();

        if (!file_close->open(QFile::ReadOnly)) {
            priz_open_file = false;
            }

        stream = new QTextStream(file_close);
        str_close = stream->readAll();
        stream->~QTextStream();

        file_close->close();
        file_close->remove();

    if(file_open != NULL)
    {
        if(!file_open->open(QFile::ReadOnly) )   {
        priz_open_file = false;
        }
        stream = new QTextStream(file_open);
        str_open = stream->readAll();
        stream->~QTextStream();
        file_open->close();
    }

    if((str_open == str_close) && (file_open != NULL))
    {
    priz_open_file = false;
    }

    bool saveDialog = false;

    if(priz_new_file || priz_open_file)
    {
        Dialog *dialog = new Dialog;
        if (dialog->exec() == QDialog::Accepted)
        {
            saveDialog = dialog->slot();
                if(saveDialog)
                {
                    on_actionSave_triggered();
                }

            priz_new_file = false;
            priz_open_file = false;
            xbelmodel->clear();
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        xbelmodel->clear();
        return true;
    }
}

void XbelView::on_actionPrint_triggered()
{
//    int PagePrint_ver = 1050,PagePrint_hor = 750;   //длина и ширина печатного листа
//    int page_count_x = 0,page_count_y = 0;    //количество страниц по x и по y
//    int max_width_pix =0, max_heigt_pix = 0;    //максимальные размеры виджета в пикселах

//    QPrinter printer;
//    QPrintDialog *dialog = new QPrintDialog(&printer, this);
//    dialog->setWindowTitle(tr("Print Document"));
//    if (dialog->exec() != QDialog::Accepted)
//        return;

//    QPainter painter;
//    painter.begin(&printer);

//    QSize size = xbelTree->size();
//    xbelTree->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
//    xbelTree->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);

//    max_width_pix = xbelTree->horizontalScrollBar()->maximum()+xbelTree->width();
//    max_heigt_pix = xbelTree->verticalScrollBar()->maximum()+xbelTree->height();

//    page_count_x = max_width_pix/PagePrint_hor ;
//    page_count_y = max_heigt_pix/PagePrint_ver;

//    if(page_count_x == 0 && page_count_y == 0)
//    {
//        xbelTree->resize(max_width_pix,max_heigt_pix);
//        xbelTree->verticalScrollBar()->hide();
//        xbelTree->horizontalScrollBar()->hide();
//        xbelTree->render(&painter);
//    }
//    else if(page_count_x == 1 && page_count_y == 0)
//    {
//        xbelTree->resize(max_width_pix,max_heigt_pix);
//        xbelTree->verticalScrollBar()->hide();
//        xbelTree->horizontalScrollBar()->hide();
//        xbelTree->render(&painter);
//        printer.newPage();
//        painter.translate(-PagePrint_hor,0);
//        xbelTree->render(&painter);
//    }
//    else if(page_count_x == 0 && page_count_y == 1)
//    {
//        xbelTree->resize(max_width_pix,max_heigt_pix);
//        xbelTree->verticalScrollBar()->hide();
//        xbelTree->horizontalScrollBar()->hide();
//        xbelTree->render(&painter);
//        printer.newPage();
//        painter.translate(PagePrint_hor,-PagePrint_ver);
//        xbelTree->render(&painter);
//    }
//    else if(page_count_x == 1 && page_count_y == 1)
//    {
//        xbelTree->resize(max_width_pix,max_heigt_pix);
//        xbelTree->verticalScrollBar()->hide();
//        xbelTree->horizontalScrollBar()->hide();
//        xbelTree->render(&painter);
//        printer.newPage();
//        painter.translate(-PagePrint_hor,0);
//        xbelTree->render(&painter);
//        printer.newPage();
//        painter.translate(PagePrint_hor,-PagePrint_ver);
//        xbelTree->render(&painter);
//        printer.newPage();
//        painter.translate(-PagePrint_hor,0);
//        xbelTree->render(&painter);
//    }
//    else
//    {
//        QMessageBox::about(0,tr("Сообщение"),tr("Слишком большое дерево!\nСообщите разработчику о необходимости доработать программу!"));
//    }

//    xbelTree->verticalScrollBar()->show();
//    xbelTree->horizontalScrollBar()->show();
//    xbelTree->resize(size);

}

void XbelView::on_actionSend_triggered()
{
            SmtpAuthData smtpAuthData;
            SmtpAuthData::Data data;
            // your email address
            data.email = "iukash.qt@gmail.com";
            // login for your email account
            data.login = "iukash.qt@gmail.com";
            // name which will be shown in From: line(optional)
            data.name = QString::fromLocal8Bit("iukash.qt@gmail.com");
            // password for auth on email account
            data.password = "iukash33";
            // port for host 587 default
            //data.port = "";
            // ssl support
            //data.enableSsl = true;
            smtpAuthData.rewriteData(data);

            Letter letter(smtpAuthData);

            QString secondFile("Hello SMTP Qt");

            QStringList filesList;
            filesList << secondFile;

            QString receivers = QString::fromLocal8Bit("iukash@rambler.ru");
            //QString blindCopyReceivers = "";
            // choice letter encoding
            //letter.set_encoding("");
            letter.set_receivers(receivers);
            //letter.set_blindCopyReceivers(blindCopyReceivers);
            letter.set_subject(QString::fromLocal8Bit("Hello SMTP Qt"));
            //letter.set_attachement(filesList);
            letter.set_text(QString::fromLocal8Bit("Hello SMTP Qt TEXT"));

            // send letter
            letter.send();

            QEventLoop eventLoop;
            eventLoop.exec();
}

void XbelView::on_actionTest_triggered()
{
    table2->resize(600,300);
    table2->show();
}
